﻿using System;
using System.Web.UI;
using System.ComponentModel;

namespace MyLib.Web.UI {
	/// <summary>
	/// 
	/// </summary>
	[ToolboxData("<{0}:MyLengthValidator runat=\"server\"></{0}:MyLengthValidator>")]
	public class MyLengthValidator : System.Web.UI.WebControls.RegularExpressionValidator {
		/// <summary>
		/// 
		/// </summary>
		private const int DefaultMaxLength = 4000;

		private bool m_initialized = false;

		/// <summary>
		/// 
		/// </summary>
		protected virtual void UpdateErrorMessage() {
			if (m_initialized) {
				if (MinLength == 0) {
					ErrorMessage = string.Format(Properties.Main.ErrorTooLong, PropertyTitle, MaxLength);
				} else if (MinLength == MaxLength) {
					ErrorMessage = string.Format(Properties.Main.ErrorInvalidLength2, PropertyTitle, MinLength);
				} else {
					ErrorMessage = string.Format(Properties.Main.ErrorInvalidLength, PropertyTitle, MinLength, MaxLength);
				}
			}
		}

		/// <summary>
		/// 
		/// </summary>
		[Category("Appearance")]
		[Bindable(true)]
		[Browsable(true)]
		[DefaultValue("")]
		public string PropertyTitle {
			get {
				var obj = ViewState["PropertyTitle"];

				return obj == null ? "" : (string)obj;
			}
			set {
				ViewState["PropertyTitle"] = value;

				UpdateErrorMessage();
			}
		}

		/// <summary>
		/// 
		/// </summary>
		[Category("Appearance")]
		[Bindable(false)]
		[Browsable(true)]
		[DefaultValue(0)]
		public int MinLength {
			get {
				var obj = ViewState["MinLength"];

				if (obj == null) {
					return 0;
				} else {
					return (int)obj;
				}
			}
			set {
				ViewState["MinLength"] = value;

				UpdateErrorMessage();
			}
		}

		/// <summary>
		/// 
		/// </summary>
		[Category("Appearance")]
		[Bindable(false)]
		[Browsable(true)]
		[DefaultValue(DefaultMaxLength)]
		public int MaxLength {
			get {
				var obj = ViewState["MaxLength"];

				if (obj == null) {
					return 0;
				} else {
					return (int)obj;
				}
			}
			set {
				ViewState["MaxLength"] = value;

				UpdateErrorMessage();
			}
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="e"></param>
		protected override void OnInit(EventArgs e) {
			base.OnInit(e);

			Display = System.Web.UI.WebControls.ValidatorDisplay.Dynamic;
			SetFocusOnError = true;

			if (string.IsNullOrWhiteSpace(ValidationExpression)) {
				ValidationExpression = string.Concat(@"^[\s|\S]{", MinLength, ",", MaxLength, @"}$");
			}

			m_initialized = true;
			if (string.IsNullOrWhiteSpace(ErrorMessage)) {
				UpdateErrorMessage();
			}
		}
	} // end of MyEmailValidator.
}
